package net.vsame.url2sql.domain;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.utils.JarUtils;

public class Url2SqlModelChain {
	private static List<Url2SqlModel> models = new ArrayList<Url2SqlModel>();
	private int i=0;
	
	public static void addModel(Url2SqlModel url2SqlModel){
		models.add(url2SqlModel);
	}
	
	/**
	 * 开始执行模块
	 */
	public static void start(){
		Url2SqlModelChain chain = new Url2SqlModelChain();
		chain.next();
	}
	
	public void next(){
		Url2SqlContext context = WebHelper.getContext();
		if(i < models.size()){
			if(!context.hasError()){
				models.get(i++).invoke(this);
			}
		}else{
			//执行Action
		}
	}
	
	/**
	 * 初始化模块
	 * @return
	 */
	public static List<Url2SqlModel> reload(){
		models.clear();
		ServiceLoader<Url2SqlModel> sl = ServiceLoader.load(Url2SqlModel.class);
		Iterator<Url2SqlModel> it = sl.iterator();
		while (it.hasNext()) {
			Url2SqlModel m = it.next();
			String jarName = JarUtils.getJarName(m.getClass());
			m.setJarName(jarName);
			models.add(m);
		}
		Collections.sort(models, new Comparator<Url2SqlModel>(){
			@Override
			public int compare(Url2SqlModel o1, Url2SqlModel o2) {
				return o1.getIndex()>o2.getIndex() ? 1 : -1;
			}
		});
		for (int i = 0; i < models.size(); i++) {
			models.get(i).init();
		}
		return models;
	}
	
}
